package com.zg.http;

import com.zg.util.BusinessException;

import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * 异常映射处理器，将会拦截所有的异常，默认设置HTTP响应码为500，如果是WebApplicationException异常，将采用WebApplicationException所带的HTTP响应码
 * 异常信息经过处理后会被转化成Response对象，该对象再经过JerseyResponseFilter的二次处理后响应该前端
 * @see WebApplicationException
 * @see JerseyResponseFilter
 * @author 王利东
 */
@Provider
public class JerseyExceptionMapper implements ExceptionMapper<Exception> {

	/**
	 * 异常处理
	 * @param e
	 * @return 异常处理后的Response对象
	 */
	@Override
	public Response toResponse(Exception e) {
		e.printStackTrace();
		
		int code = Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
		if (e instanceof NotFoundException) {
			code = Response.Status.NOT_FOUND.getStatusCode();
		} else if (e instanceof WebApplicationException) {
			code = WebApplicationException.class.cast(e).getResponse().getStatus();
		} else if (e instanceof BusinessException) {
			code = BusinessException.class.cast(e).getCode();
		}
		
		ResponseBean.no(code, e.getMessage());
		
		return null;
	}
}